package Part4_反射的应用;

import Part4_反射的应用.data.Person;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * ClassName: Apply
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.05.08 13:12
 */
public class Apply {

    /*
     * 反射：调用指定的属性
     * @throws ClassNotFoundException
     */
    @Test
    public void test1() throws InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();

        Field ageField = personClass.getField("age");
        //设置属性值
        ageField.set(person,12);
        //获取属性值
        int age = (int) ageField.get(person);
        System.out.println(age);
    }

    /*
     * 反射：调用指定的方法
     * @throws ClassNotFoundException
     */
    @Test
    public void test2() throws InstantiationException, IllegalAccessException,
            NoSuchMethodException, InvocationTargetException {

        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();

        Method showNationMethod = personClass.getDeclaredMethod("showNation", String.class, int.class);

        showNationMethod.setAccessible(true);

        String info = (String) showNationMethod.invoke(person, "China", 25);
        System.out.println(info);
    }

}
